package study.三种方式实现生产者消费者模式.waitAndNotify;

import java.util.ArrayList;

//仓库
public class Storer {
	
	private static int MAX_NUMBER=20;
	private ArrayList<Object> aList = new ArrayList<>();

	public void produce (int number)
	{
		synchronized (aList) 
		{
			if( aList.size()+number > MAX_NUMBER )
			{
				System.out.println("需要生产的产品数量："+number+",仓库已满，停止生产！");
				try 
				{
					aList.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("生产线程名字："+Thread.currentThread().getName()+"，number="+number);

			for (int i = 0; i < number; i++) {
				aList.add(new Object());
			}
			aList.notifyAll();			
		}
	}
	
	//消费者
	public void consume(int number)
	{
		synchronized (aList) 
		{
			if( aList.size() - number<0)
			{
				System.out.println("仓库存储不足，不能消费"+number+"个消费品！");
				try {
					aList.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("消费线程名字："+Thread.currentThread().getName()+"，number="+number);
//			if( aList.size()-number >0 )
			for (int i = 0; i < number; i++) {
				aList.remove(0);
			}
			aList.notifyAll();
		}
	}
}
